using System;
using System.Data;
using System.Data.Common;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using MagnoliaTableAdapters;
using System.Data.SqlClient;
using System.IO;
using System.Text.RegularExpressions;
using Subgurim.Controles;

public partial class ImageTag : System.Web.UI.Page
{
    static int imageTagID;
    static int rowID;
    static int editIndex;
    static string fName;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (FileUploaderAJAX1.IsPosting)
        {
            ManagePost();
        }
        Page.Title = ConfigurationManager.AppSettings["PageTitle"] + " - Image Tags";
        hiddenFilePath.Style.Add("display", "none");

        // hide edit and delete buttons for user access
        GridView1.Columns[0].Visible = false;
        // hide save row
        if (GridView1.Rows.Count > 0)
            GridView1.FooterRow.Visible = false;

        // get user access permissions
        DataTable UserAccessDT = (DataTable)Session["UserAccess"];
        foreach (DataRow dr in UserAccessDT.Rows)
        {
            // edit image tag
            if (Convert.ToString(dr.ItemArray[0]) == "324")
            {
                GridView1.Columns[0].Visible = true;
            }
            // new image tag
            if (Convert.ToString(dr.ItemArray[0]) == "424")
            {
                if (GridView1.Rows.Count > 0)
                    GridView1.FooterRow.Visible = false;
            }

        }
    }

    protected void ManagePost()
    {
        HttpPostedFileAJAX pf = FileUploaderAJAX1.PostedFile;

        //string command = "Select value from Globalconfig where Property = 'ImageTagJPEGPath'";
        //string imageTagPath = getDataObject(command).ToString();

        Regex fileRegex = new Regex("^[a-zA-Z0-9_ -]*_[0-9]+.[a-zA-Z0-9_]{3}$");
        if (!fileRegex.IsMatch(pf.FileName))
        {
            ResetHidden();
            FileUploaderAJAX1.PostedFile.responseMessage_Uploaded_NotSaved = "&#149; The filename for the uploaded image must be formatted as \"name_xxx.extension\" where \"xxx\" represents the pixel width (e.g. \"my_image_200.jpg\")";

            return;
        }
        else
        {

            fName = @"Y:/" + pf.FileName;
            string nameFile = pf.FileName;

            string filePath = Server.MapPath("UploadData") + "\\" + nameFile;
            string fileRaidPath = @"C:\UploadImage\" + nameFile;

            //if (!Directory.Exists(imageTagPath))
            //    Directory.CreateDirectory(imageTagPath);

            FileUploaderAJAX1.SaveAs("UploadData", nameFile);

            File.Copy(filePath, fileRaidPath, true);
            File.Delete(filePath);
        }
    }
    private bool LoadDataEmpty
    {
        //  some controls that are used within a GridView, such as the calendar control, can cuase post backs.
        //  we need to preserve LoadDataEmpty across post backs.
        get { return (bool)(ViewState["LoadDataEmpty"] ?? false); }
        set { ViewState["LoadDataEmpty"] = value; }
    }

    protected void GridView_RowCreated(object sender, GridViewRowEventArgs e)
    {
        //  when binding a row, look for a zero row condition based on the flag.
        //  if we have zero data rows (but a dummy row), hide the grid view row
        //  and clear the controls off of that row so they don't cause binding errors
        if (LoadDataEmpty && e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Visible = false;
            e.Row.Controls.Clear();
        }
    }

    protected void GridView_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        ////  handle the save button on the footer row. this is the only manual data operation
        ////  that must be done. update and delete are handled by the gridview and ODS
        Lbl_EditorAlerts.Visible = false;
        
        string name;
        string imagePath;
        string lastUpdated;

        if (e.CommandName == "Save")
        {
            name = ((TextBox)GridView1.FooterRow.FindControl("TextBoxName")).Text;
            
            bool pass = ValidateInput(-1, name);
            if (!pass)
                return;
            
            imagePath = fName;
            lastUpdated = DateTime.Now.ToString();
            SqlDataSource1.InsertCommand = "sproc_WEB_InsertImageTag @Name ='" + name + "', @ImagePath ='" + imagePath + "', @LastUpdated='" + lastUpdated + "' ,@InUseNN='true'";

            SqlDataSource1.Insert();
            GridView1.DataBind();
            ResetHidden();
        }
        if (e.CommandName == "SelfUpdate")
        {
            name = ((TextBox)GridView1.Rows[rowID - 1].FindControl("TextBoxName")).Text;

            bool pass = ValidateInput(imageTagID, name);
            if (!pass)
                return;

            if (editIndex == 1 || fName == null)  // fName == null is for cases where user aborts a bad upload
                imagePath = ((Label)GridView1.Rows[rowID - 1].FindControl("LabelImagePath")).Text;
            else
                imagePath = fName;

            lastUpdated = DateTime.Now.ToString();
            SqlDataSource1.UpdateCommand = "UPDATE [IMAGETAG] SET [Name] ='" + name + "' , [ImagePath] = '" + imagePath + "', [lastUpdated]= '" + lastUpdated + "' WHERE [ID] = " + imageTagID;

            SqlDataSource1.Update();

            GridView1.DataBind();
            ResetHidden();
        }
        if (e.CommandName == "Cancel" || e.CommandName == "Edit" || e.CommandName == "Delete")
        {
            ResetHidden();
        }
    }

    protected void ResetHidden()
    {
        hiddenFilePath.Text = "";

        fName = null;

        FileUploaderAJAX1.Visible = false;

        FileUploaderAJAX1.Reset();
    }

    //Get the SQL command and return single object item using DataReader to speed up the communication
    protected object getDataObject(string selectSQL)
    {

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SuperSignConnectionString"].ConnectionString);
        SqlCommand cmd = new SqlCommand(selectSQL, con);
        SqlDataReader reader = null;
        object ob = new object();

        try
        {
            con.Open();
            reader = cmd.ExecuteReader();
            reader.Read();
            ob = reader[0];//Only read ONE data in the first of list
            reader.Close();

        }
        catch (Exception err)
        {
        }
        finally
        {
            con.Close();
        }
        return ob;
    }
    protected void hiddenFilePath_TextChanged(object sender, EventArgs e)
    {
        string[] path = hiddenFilePath.Text.Split('?');
        imageTagID = Convert.ToInt32(path[0]);
        rowID = Convert.ToInt32(path[1]);
        int index = Convert.ToInt32(path[2]);

        if (index == 2)
            editIndex = 2;

        if (editIndex == null || editIndex == 0)
            editIndex = index;

        if (editIndex == 2)
            FileUploaderAJAX1.Visible = true;
        else
            FileUploaderAJAX1.Visible = false;
    }
    public bool ValidateInput(int tagID, string tagName)
    {
        bool pass = true;     

        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SuperSignConnectionString"].ConnectionString);
        try
        {
            conn.Open();

            String sProc = "sproc_WEB_DoesTagNameExist";

            SqlCommand cmd = new SqlCommand(sProc, conn);
            cmd.CommandType = CommandType.StoredProcedure;

            // set paramter
            DbParameter param = cmd.CreateParameter();
            param.ParameterName = "@Name";
            param.Value = Convert.ToString(tagName.Trim());
            param.DbType = DbType.String;
            cmd.Parameters.Add(param);

            DbDataReader reader = cmd.ExecuteReader();
            DataTable dt = new DataTable();
            dt.Load(reader);
            reader.Close();

            int returnedID = Convert.ToInt32(dt.Rows[0].ItemArray[0]);

            if ((returnedID != 0 && returnedID != tagID)
                || (returnedID != 0 && Convert.ToInt32(dt.Rows[0].ItemArray[1]) != 23))
            {
                pass = false;
                int returnedLevel = Convert.ToInt32(dt.Rows[0].ItemArray[1]);
                if (returnedLevel == 21)
                    Lbl_EditorAlerts.Text = "&#149; This tag name already exists as a data tag, please use a different tag name";
                else if (returnedLevel == 22)
                    Lbl_EditorAlerts.Text = "&#149; This tag name already exists as a string tag, please use a different tag name";
                else if (returnedLevel == 23)
                    Lbl_EditorAlerts.Text = "&#149; This tag name already exists as an image tag, please use a different tag name";
                Lbl_EditorAlerts.Visible = true;
            }
        }
        catch (Exception ex)
        {
            String err = ex.Message;
        }
        finally
        {
            conn.Close();
        }

        return pass;
    }
}
